
import { compare, lineEquation } from '../common.js'

export default class Line {
  constructor(ctx){
    this.Ctx = ctx;
  }

  // 绘制线
  line(info,save = true,reload = true){
    this.Ctx.ctx.save()
    if(info.auxProps) {
      for(let [k, v] of Object.entries(info.auxProps)) {
        this.Ctx.ctx[k] = v;
      }
    }
    let {x,y,endX,endY,id = new Date().getTime(),fillColor,lineWidth=1,textInfo, level = 1} = info
    if(reload) this.Ctx.repaint();
    this.lineBegin({...info, x,y,id,textInfo,level},save);
    this.Ctx.ctx.lineWidth = lineWidth || 1;
    this.Ctx.ctx.strokeStyle = fillColor || "rgb(0,0,0)";
    let ele = this.lineTo({endX,endY,id,lineWidth,fillColor},save);
    this.Ctx.ctx.restore()
    return ele;
  }
  lineBegin(info ,save = true){
    let {x,y,id,textInfo,level} = info;
    this.Ctx.ctx.beginPath();
    this.Ctx.ctx.moveTo(x,y);
    if(save) {
      this.Ctx.canvasInfoMap.set(id, {...info, id,type:'line',x,y,textInfo,level})
    }
  }
  lineTo({endX,endY,id,fillColor,lineWidth},save = true){
    this.Ctx.ctx.lineTo(endX,endY);
    this.Ctx.ctx.closePath();
    this.Ctx.ctx.stroke();
    if(save){
      let ele = this.Ctx.canvasInfoMap.get(id);
      ele.endX = endX;
      ele.endY = endY;
      ele.fillColor = fillColor || "rgb(0,0,0)";
      ele.lineWidth = lineWidth || 1;

      let x1 = ele.x;
      let x2 = endX;
      let y1 = ele.y;
      let y2 = endY;
      let obj = lineEquation(ele);  // 计算直角坐标方程（返回a,b,c，方便计算点到直线的距离）
      let obj1 = compare([[x1,y1],[x2,y2]])
      // 当线条为水平或者垂直线的时候，需要扩大点击范围
      if(obj.a === 0){  // 横线
        obj1.minY -= 10;
        obj1.maxY += 10;
      }else{            // 竖线
        obj1.minX -= 10;
        obj1.maxX += 10;
      }

      Object.assign(ele,obj,obj1)
      this.Ctx.canvasInfoMap.set(id, ele)
      return ele
    }
  }
}